
#include "../include/N_arytree.h"
int list_dir(t_node** root,char*dir_name,int flag, char*outputfile)
{
	if(flag!=0 && flag!=1)
		{
			//#define ERR_VFS_LISTDIR_02 "INVALID_FLAG"
			return 1;
		}
	t_node *current;
	t_node *d;
	char **tokens=NULL;
	int cnt=1,count,i,flag1=1;
        FILE *fp;


       fp = fopen(outputfile, "w");
	if(fp == NULL) {
		
		//fclose(fp);
		//#define ERR_VFS_LISTDIR_04 <CANNOT_CREATE_OUTPUTFILE>"
		return 3;
	}


	count=generate_tokens(&tokens,dir_name,'/');
 
	i = 0;
	current = *root;
	//Traversing source dir
	while(current != NULL)
	{
		if(current->is_deleted == 0 && strcmp(current->data->file_name,tokens[i]) == 0 && current->data->fileType=='D')
		{
			i++;
			if(i == count)
				break;
			current = current->left_child;
			
		}
		//Goto right siblings
		else if(current->right_siblings != NULL)
		{
			current = current->right_siblings;
		}
		else
		{
			flag1 =0;
			break;
		}
	}
	
	
	//Invalid positions
	if(flag1== 0 || current == NULL)
	{	//printf("%s",dir_name);
		//#define ERR_VFS_LISTDIR_01 <CANNOT_FIND_SPECIFIED_PATH_OR_DIR>"
		return 2;
	}
	
	fp = fopen(outputfile, "w");
		     fclose(fp);
	if(current->left_child!=NULL)
	{if(flag==0)
		write_to_file(current->left_child,outputfile);
	else if(flag==1)
	        write_to_file_recursive(current->left_child,outputfile);
	}

	fp = fopen(outputfile, "r");
	if(fp == NULL) {
		
		//fclose(fp);
		//#define ERR_VFS_LISTDIR_04 <CANNOT_CREATE_OUTPUTFILE>"
		return 3;
	}
	return 0;

}
//This function write entire subtree to outputfile
int write_to_file_recursive(t_node *root,char *outputfile)
{	

	FILE *fp;
	
        if(root!=NULL && root->is_deleted!=1)
	{  
		fd* f = root->data;
    	
	fp = fopen(outputfile, "a+");
	
	fwrite(f->file_name,strlen(f->file_name),1,fp);
	fputc('\n',fp);
	fwrite("FileType:",9,1,fp);
	fputc(f->fileType,fp);
	fputc('\n',fp);
	fwrite("Path:",5,1,fp);
	fwrite(f->path,strlen(f->path),1,fp);
	fputc('\n',fp);
  	fclose(fp);
	
       
 	}
	 if(root->left_child!=NULL)
  	    write_to_file_recursive(root->left_child,outputfile);
  	if(root->right_siblings!=NULL)
    	    write_to_file_recursive(root->right_siblings,outputfile);
   return 0;
}
//this function child of source dir only to one level to output file
int write_to_file(t_node *root,char*outputfile)
{	
	FILE *fp;
	
   	 if(root!=NULL && root->is_deleted!=1)
	{  
		fd* f = root->data;
    	
  	fp = fopen(outputfile, "a+");
	fwrite(f->file_name,strlen(f->file_name),1,fp);
	fputc('\n',fp);
	fwrite("FileType:",9,1,fp);
	fputc(f->fileType,fp);
	fputc('\n',fp);
	fwrite("Path:",5,1,fp);
	fwrite(f->path,strlen(f->path),1,fp);
	fputc('\n',fp);
  	fclose(fp);
	
	}
	if(root->right_siblings!=NULL)
    	write_to_file(root->right_siblings,outputfile);
 	return 0;
}
